<?php

define("FUNC_BASE_URL", '/index.php?s=/w');
define("APPROVAL_TYPE_REIMBURSEMENT",3);

function msg_reimbursementInPool($apply){
    $data = [
        'keyword1'=>[
            'value'=> $apply['subtype'],
            'color' => '#173177'
        ],
        'keyword2'=>[
            'value'=> M('OaEmployee')->where(array('id'=>$apply['applyer']))->getField('name'),
            'color' => '#173177'
        ],
        'keyword3'=>[
            'value'=> $apply['total_money'],
            'color' => '#173177'
        ],
        'keyword4'=>[
            'value'=>date('Y-m-d H:i:s',$apply['submit_date']),
            'color' => '#173177'
        ],
        'keyword5'=>[
            'value'=> '有新的财务报销审批任务单('.$apply['apply_no'].'),请尽快领取。',
            'color' => '#173177'
        ]
    ];
    return $data;
}
function msg_reimbursementTook($apply){
    $data = [
        'keyword1'=>[
            'value'=> $apply['subtype'],
            'color' => '#173177'
        ],
        'keyword2'=>[
            'value'=> M('OaEmployee')->where(array('id'=>$apply['applyer']))->getField('name'),
            'color' => '#173177'
        ],
        'keyword3'=>[
            'value'=> $apply['total_money'],
            'color' => '#173177'
        ],
        'keyword4'=>[
            'value'=> date('Y-m-d H:i:s',$apply['submit_date']),
            'color' => '#173177'
        ],
        'keyword5'=>[
            'value'=> '您有新的财务报销审批任务单('.$apply['apply_no'].')',
            'color' => '#173177'
        ]
    ];
    return $data;
}
function msg_reimbursementRefused($apply){
    $data = [
        'keyword1'=>[
            'value'=> $apply['subtype'],
            'color' => '#173177'
        ],
        'keyword2'=>[
            'value'=> M('OaEmployee')->where(array('id'=>$apply['applyer']))->getField('name'),
            'color' => '#173177'
        ],
        'keyword3'=>[
            'value'=> $apply['total_money'],
            'color' => '#173177'
        ],
        'keyword4'=>[
            'value'=> date('Y-m-d H:i:s',$apply['submit_date']),
            'color' => '#173177'
        ],
        'keyword5'=>[
            'value'=> '报销审批任务单('.$apply['apply_no'].'),被驳回了！',
            'color' => '#173177'
        ]
    ];
    return $data;
}

function msg_reimbursementDone($apply){
    $data = [
        'keyword1'=>[
            'value'=> $apply['subtype'],
            'color' => '#173177'
        ],
        'keyword2'=>[
            'value'=> M('OaEmployee')->where(array('id'=>$apply['applyer']))->getField('name'),
            'color' => '#173177'
        ],
        'keyword3'=>[
            'value'=> $apply['total_money'],
            'color' => '#173177'
        ],
        'keyword4'=>[
            'value'=> date('Y-m-d H:i:s',$apply['submit_date']),
            'color' => '#173177'
        ],
        'keyword5'=>[
            'value'=> '报销审批任务单('.$apply['apply_no'].'),已审批完成！',
            'color' => '#173177'
        ]
    ];
    return $data;
}
/**
 * 生成审批单号
 *
 * @param string $typeNo
 *        	类型编号
 * @param string $depId
 *        	部门编号
 * @param int $applyId
 *        	oa_application 主键ID

 */
function generateApplyNo($typeNo='', $applyId=0)
{
    if (empty($typeNo) || empty($applyId)){
        return '';
    }
    $date = date('ymd', time());
    $tmpId = ($applyId > 1000000)?str($applyId):substr(strval((intval(1000000)+intval($applyId))),1,6);
    $sn = $typeNo.$date.$tmpId;
    return $sn;
}

/**
 * 查看员工访问节点的权限
 *
 * @param int $node_id
 *        	节点ID
 * @param int $emp_id
 *        	部门编号
 * @param bool $appurl
 *        	是否为小程序Url*
    return True:  有权限; False: 没有权限
 */
function checkNodeAccessRight($node_id=0,$emp_id=0,$appurl=true){
    if (empty($node_id) || empty($emp_id) ){
        return false;
    }
    $node_map['id'] = $node_id;
    $node = M('OaNode')->where($node_map)->find();
    $nodeUrl = FUNC_BASE_URL.WPID.'/'.($appurl?$node['app_url']:$node['url']);

    // var_dump('checkNodeAccessRight 1',$nodeUrl);
    // var_dump($_SERVER["REQUEST_URI"]);
    // var_dump($nodeUrl);
    // var_dump($_SERVER["REQUEST_URI"]);
    if ($nodeUrl !== $_SERVER["REQUEST_URI"]){
        return false;
    }
    // var_dump('checkNodeAccessRight 2');
    $rn_map['node_id'] = $node_id;
    $roleNodes = M('OaRoleNode')->where($rn_map)->select();

    if(empty($roleNodes)) {
        return true;
    }
    // var_dump('checkNodeAccessRight 3');
    foreach ($roleNodes as $roleNode) {
        $er_map['emp_id'] = $emp_id;
        $er_map['role_id'] = $roleNode['role_id'];
        $empRole = M('OaUserRole')->where($er_map)->find();
        if(!empty($empRole)){
            return true;
        }
    }
    // var_dump('checkNodeAccessRight 4');
    return false;
}

/**
 * 获取员工所有的访问节点
 *
 * @param int $emp_id
 *        	员工ID
return array [] 节点列表
 */
function getEmpAllaccessNode($emp_id){
    $nodes = Array();
    $er_map['emp_id'] = $emp_id;
    // var_dump("getEmpAllaccessNode: empid:".$emp_id);
    $empRoles = M('OaUserRole')->where($er_map)->select();
    foreach ($empRoles as $empRole) {
        $rn_map['role_id'] = $empRole['role_id'];
        $roleNodes = M('OaRoleNode')->where($rn_map)->select();
        foreach ($roleNodes as $roleNode) {
            if(!in_array($roleNode['node_id'],$nodes)){
                // var_dump($roleNode);
                array_push($nodes,$roleNode['node_id']);
            }
        }
    }
    return $nodes;
}

/**
 * 流程跳转check
 *
 * @param array $apply_data
 *        	前端上传过来的数据
 * @param array $old_data
 *        	数据库取出的数据
 * @param  $cur_emp_id
 *        	当前访问的员工ID*
return True:  有权限; False: 没有权限
 */
function checkApprovalHop($apply_data,$old_data,$cur_emp_id){
    $map['id'] = $apply_data['flow_id'];
    $process = M('OaProcessFlow')->where($map)->find();
    $return['errcode'] = 0;

    if(empty($process)) {
        $return['errcode'] = '61451';
        $return['msg'] = error_msg($return,'flow_id 数据错误');
        return $return;
    }

    if($apply_data['step'] != ($old_data['step']+1)){
        $return['errcode'] = '61451';
        $return['msg'] = error_msg($return,'step 数据错误');
        return $return;
    }

    if($old_data['approver'] != $cur_emp_id) {
        $return['errcode'] = '50002';
        $return['msg'] = error_msg($return,' 需要当前经办人处理');
        return $return;
    }

    return $return;
}
/**
 * 谁拥有这个角色 whoHasTheRole
 *
 * @param roleid
 *        	角色ID
 *        	数据库取出的数据
return  employees[]
 */
function whoHasTheRole($roleid) {
    $map['role_id'] = $roleid;
    $employees = D('OaUserRoleEmployeeView')->where($map)->select();
    $data['count'] = count($employees);
    $data['emps'] = $employees;
    return $data;
}

function findallDeptsInThisDept($thisDeptId,&$deptIds) {
    $depts = M('OaDept')->where(array('pid'=>$thisDeptId))->field('id')->select();
    if(!empty($depts)) {
        foreach ($depts as $dept) {
            $tmpIds = findallDeptsInThisDept($dept['id'],$deptIds);
        }
    }
    $deptIds = array_merge($deptIds,[$thisDeptId]);
    return $deptIds;
}

function findallDeptsInTargetGrade($empDeptView,$target_grade){
    $deptIds = array();
    if ($empDeptView['grade_value'] > $target_grade) {
        $empDept = D('OaDeptView')->where(array('id'=>$empDeptView['dept_id']))->find();
        $targetDept = findTargetDetp($empDept,$target_grade);
        if (!empty($targetDept)) {
            findallDeptsInThisDept($targetDept['id'],$deptIds);
        }
    } else {
        array_push($deptIds, $empDeptView['dept_id']);
    }
    
    return $deptIds;
}

function findTargetDetp ($dept,$target_grade) {
    if (($dept['grade_value'] > $target_grade) && ($target_grade != 0) && ($dept['pid'] != 0)) {
        $tmp = $dept;
        do{
            $tmp = D('OaDeptView')->where(array('id'=>$tmp['pid']))->find();
            if(empty($tmp)) {
                $return['errcode'] = '50002';
                $return['msg'] = error_msg($return,' 未找到目标部门');
                var_dump($return);
                return null;
            }
        }while(($tmp['grade_value'] > $target_grade) && ($tmp['pid'] != 0));
        return $tmp;
    } else {
        return $dept;
    }
}

function getWhoHasTheRightAccessThisNode($node_id,$applyer_dept) {
    if (empty($node_id)){
        return null;
    }
    $applyerDept = D('OaDeptView')->where(array('id'=>$applyer_dept))->find();
    $node = M('OaNode')->where(array('id'=>$node_id))->find();
    $targetDept = findTargetDetp($applyerDept,$node['dept_grade']);
    if(empty($targetDept)) {
        return null;
    }
    $emp_list = [];
    $rn_map['node_id'] = $node_id;
    $roleNodes = M('OaRoleNode')->where($rn_map)->select();
    if(empty($roleNodes)) {
        return $emp_list;
    }

    foreach ($roleNodes as $roleNode) {
        $er_map['role_id'] = $roleNode['role_id'];
        $empRoles = D('OaUserRoleEmployeeView')->where($er_map)->select();
        if(!empty($empRoles)) {
            foreach ($empRoles as $empRole) {
                if(!in_array($empRole['emp_id'],$emp_list,true)){
                    if ($node['scope'] == 'S' ) {   // 部门级部门一下的域
                        if($applyerDept['grade_value'] >= $node['dept_grade']) {
                            if($empRole['dept_id'] == $targetDept['id']){
                                // 审批人所在的部门ID 和 申请单目标部门一致
                                array_push($emp_list,$empRole['emp_id']);
                            } else if ($empRole['grade_value'] > $node['dept_grade']) {
                                // grade_value 值越大，部门的级别越低
                                // 审批人所在的部门级别低于申请单目标部门级别，查找审批人对应级别的部门ID,
                                // 如果审批人的对应级别的部门ID 和 单子目标部门一致，则加入列表
                                $approverDept = D('OaDeptView')->where(array('id'=>$empRole['dept_id']))->find();
                                $approverTargetDept = findTargetDetp($approverDept,$node['dept_grade']);
                                if ($approverTargetDept['id'] == $targetDept['id']) {
                                    array_push($emp_list,$empRole['emp_id']);
                                }
                            } else if ($empRole['grade_value'] <= $node['dept_grade']) {
                                // grade_value 值越大，部门的级别越低
                                // 审批人部门的级别是同级或更高， 审批人可能是身兼数个职能部门的领导，或者更高领导下派管理低级部门
                                if ((!empty($empRole['role_deptid'])) && ($empRole['role_deptid'] == $targetDept['id'])) {
                                    // 审批人角色里面的部门id 跟申请单目标部门id一致
                                    array_push($emp_list,$empRole['emp_id']);
                                }
                            }
                        } else {
                            if($empRole['dept_id'] == $targetDept['id']) {
                                array_push($emp_list, $empRole['emp_id']);
                            }
                        }
                    } else {  // 全局域
                        array_push($emp_list,$empRole['emp_id']);
                    }
                }
            }
        }
    }
    $emp_list = array_unique($emp_list);
    return $emp_list;
}

function myprint($name = NULL, $data)
{
    echo "<pre>";
    print_r($name.' = ');
    print_r($data);
    echo "</pre>";
}

function db_select($model, $map = null, $order = null, $field = null) {
    if($model == 'oa_employee') {
        $map['is_left'] = 0;
    }
    $map['appid'] = get_app_info()['appid'];
    $res = M($model)->where($map)->order($order)->field($field)->select();
    return $res;
}

function db_find($model, $map = null, $order = null, $field = null) {
    if($model == 'oa_employee') {
        $map['is_left'] = 0;
    }
    $map['appid'] = get_app_info()['appid'];
    $res = M($model)->where($map)->order($order)->field($field)->find();
    return $res;
}

function db_save($model, $map, $data) {
    $map['appid'] = get_app_info()['appid'];
    $res = M($model)->where($map)->save($data);
    return $res;
}